import { useState, useEffect } from 'react';
import { toast } from 'sonner';
import AdminLayout from '@/components/admin/AdminLayout';
import { cn } from '@/lib/utils';
import { useCompanyInfo, useUpdateCompanyInfo, useCreateCompanyInfo } from '@/hooks/useCompany';
import { CompanyInfo } from '@/types';

export default function ContactInfoManagement() {
  const [isEditing, setIsEditing] = useState(false);

  // 使用API hooks
  const { data: companyInfo, isLoading, error } = useCompanyInfo();
  const updateCompanyInfo = useUpdateCompanyInfo();
  const createCompanyInfo = useCreateCompanyInfo();

  // 表单状态
  const [formData, setFormData] = useState({
    company_name: '',
    address: '',
    phone: '',
    email: '',
    website: '',
    fax: ''
  });

  // 初始化表单数据
  useEffect(() => {
    if (companyInfo) {
      setFormData({
        company_name: companyInfo.company_name || '',
        address: companyInfo.address || '',
        phone: companyInfo.phone || '',
        email: companyInfo.email || '',
        website: companyInfo.website || '',
        fax: companyInfo.fax || ''
      });
    }
  }, [companyInfo]);
  
  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: value
    }));
  };

  // 切换编辑状态
  const toggleEdit = () => {
    setIsEditing(!isEditing);

    // 如果取消编辑，重置表单数据
    if (isEditing && companyInfo) {
      setFormData({
        company_name: companyInfo.company_name || '',
        address: companyInfo.address || '',
        phone: companyInfo.phone || '',
        email: companyInfo.email || '',
        website: companyInfo.website || '',
        fax: companyInfo.fax || ''
      });
    }
  };
  
  // 保存联系信息
  const saveContactInfo = async () => {
    // 验证必填字段
    if (!formData.company_name || !formData.address || !formData.phone || !formData.email) {
      toast.error('请填写所有必填字段');
      return;
    }

    try {
      if (companyInfo) {
        // 更新现有公司信息
        await updateCompanyInfo.mutateAsync(formData);
      } else {
        // 创建新的公司信息
        await createCompanyInfo.mutateAsync(formData);
      }

      setIsEditing(false);
      toast.success('联系信息更新成功');
    } catch (error) {
      console.error('保存联系信息失败:', error);
      toast.error('保存失败，请重试');
    }
  };
  
  if (isLoading) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center min-h-[500px]">
          <div className="text-center">
            <i className="fa-solid fa-spinner fa-spin text-3xl text-blue-600 mb-4"></i>
            <p className="text-gray-600">加载中...</p>
          </div>
        </div>
      </AdminLayout>
    );
  }
  
  // 加载状态
  if (isLoading) {
    return (
      <AdminLayout>
        <div className="flex justify-center items-center py-12">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
          <span className="ml-3 text-gray-600">加载联系信息...</span>
        </div>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout>
      <div className="flex flex-col md:flex-row md:items-center md:justify-between mb-6">
        <div>
          <h1 className="text-2xl font-bold text-gray-800">联系信息管理</h1>
          <p className="text-gray-600">管理公司联系信息和联系方式</p>
        </div>
        <button
          type="button"
          onClick={isEditing ? saveContactInfo : toggleEdit}
          className={`mt-4 md:mt-0 font-medium py-2 px-4 rounded-lg transition-colors flex items-center ${
            isEditing
              ? 'bg-blue-600 hover:bg-blue-700 text-white'
              : 'bg-gray-100 hover:bg-gray-200 text-gray-700'
          }`}
          disabled={updateCompanyInfo.isPending || createCompanyInfo.isPending}
        >
          {(updateCompanyInfo.isPending || createCompanyInfo.isPending) ? (
            <>
              <i className="fa-solid fa-spinner fa-spin mr-2"></i> 保存中...
            </>
          ) : isEditing ? (
            <>
              <i className="fa-solid fa-save mr-2"></i> 保存信息
            </>
          ) : (
            <>
              <i className="fa-solid fa-edit mr-2"></i> 编辑信息
            </>
          )}
        </button>
      </div>
      
      {/* 联系信息卡片 */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
        {/* 基本联系信息 */}
        <div className="lg:col-span-2 bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
          <div className="p-6 border-b">
            <h2 className="text-lg font-bold text-gray-800">基本联系信息</h2>
          </div>
          
          <div className="p-6 space-y-6">
            <div>
              <label className="block text-sm font-medium text-gray-500 mb-1">公司名称</label>
              {isEditing ? (
                <input
                  type="text"
                  name="company_name"
                  value={formData.company_name}
                  onChange={handleInputChange}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                  placeholder="请输入公司名称"
                />
              ) : (
                <p className="text-gray-800 font-medium">{companyInfo?.company_name || '未设置'}</p>
              )}
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-500 mb-1">公司地址</label>
              {isEditing ? (
                <textarea
                  name="address"
                  value={formData.address}
                  onChange={handleInputChange}
                  rows={2}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                  placeholder="请输入公司地址"
                ></textarea>
              ) : (
                <p className="text-gray-600">{companyInfo?.address || '未设置'}</p>
              )}
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label className="block text-sm font-medium text-gray-500 mb-1">联系电话</label>
                {isEditing ? (
                  <input
                    type="tel"
                    name="phone"
                    value={formData.phone}
                    onChange={handleInputChange}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                    placeholder="请输入联系电话"
                  />
                ) : (
                  <p className="text-gray-600">{companyInfo?.phone || '未设置'}</p>
                )}
              </div>

              <div>
                <label className="block text-sm font-medium text-gray-500 mb-1">电子邮箱</label>
                {isEditing ? (
                  <input
                    type="email"
                    name="email"
                    value={formData.email}
                    onChange={handleInputChange}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                    placeholder="请输入电子邮箱"
                  />
                ) : (
                  <p className="text-gray-600">{companyInfo?.email || '未设置'}</p>
                )}
              </div>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label className="block text-sm font-medium text-gray-500 mb-1">官方网站</label>
                {isEditing ? (
                  <input
                    type="url"
                    name="website"
                    value={formData.website}
                    onChange={handleInputChange}
                    className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                    placeholder="请输入官方网站"
                  />
                ) : (
                  companyInfo?.website ? (
                    <a
                      href={companyInfo.website}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-blue-600 hover:text-blue-800"
                    >
                      {companyInfo.website}
                    </a>
                  ) : (
                    <p className="text-gray-600">未设置</p>
                  )
                )}
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-gray-500 mb-1">传真号码</label>
              {isEditing ? (
                <input
                  type="tel"
                  name="fax"
                  value={formData.fax}
                  onChange={handleInputChange}
                  className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                  placeholder="请输入传真号码"
                />
              ) : (
                <p className="text-gray-600">{companyInfo?.fax || '未设置'}</p>
              )}
            </div>
          </div>
        </div>
      </div>
      
      {!isEditing && (
        <div className="bg-blue-50 border border-blue-100 rounded-xl p-6">
          <h3 className="text-lg font-semibold text-blue-800 mb-3 flex items-center">
            <i className="fa-solid fa-info-circle mr-2"></i> 编辑提示
          </h3>
          <p className="text-blue-700">
            点击"编辑信息"按钮可以修改联系信息。修改后的信息将实时更新到网站前台的联系我们页面。
          </p>
        </div>
      )}
    </AdminLayout>
  );
}
